import './WijmoFlexGrid.scss'

import { Dropdown } from 'antd'
import { useState } from 'react'
import { useReactive, useEventEmitter } from 'ahooks'


import { PivotEngine } from '@grapecity/wijmo.olap';
import { PivotGrid } from '@grapecity/wijmo.react.olap';
import { FlexGridFilter } from "@grapecity/wijmo.react.grid.filter"
import { GroupPanel } from "@grapecity/wijmo.react.grid.grouppanel"
import { Row, DataMap, GroupRow, CellRange } from '@grapecity/wijmo.grid'
import { CollectionView, SortDescription, saveFile, Globalize } from '@grapecity/wijmo'
import { FlexGrid, FlexGridColumn, FlexGridCellTemplate } from '@grapecity/wijmo.react.grid'
import { MultiRow, MultiRowCell, MultiRowCellGroup, MultiRowCellTemplate } from '@grapecity/wijmo.react.grid.multirow'

import { objectArrValue } from '../../Utils/configFun'

import { ModelBox } from '..'




const WijmoFlexGrid = ({ data }) => {
    const { itemsSource, gridConfig } = data
    const { configuration, initParameter, columns, optionsBtn } = gridConfig
    const { addBtm, addSum, addIndex, topText, btmText, filter } = initParameter
    const InitWijmo = useReactive({ init: null })

    const [Data, setData] = useState()
    const [OptionsCall, setOptionsCall] = useState()

    const init = (e) => {
        InitWijmo.init = e
        const data = itemsSource.collectionView
        if (addBtm || addSum) e.columnFooters.rows.push(addSum ? new GroupRow() : new Row())
        setData(data)
    }

    const getDataMap = (e) => {
        const data = Object.keys(e).map((key) => ({ value: key, label: e[key].text || e[key] }))
        return new DataMap(data, 'value', 'label')
    }
    const CustonGroup = (e) => {
        if (e.col.aggregate !== 0) {
            const { aggTitle, format } = objectArrValue(columns, e.col.binding, 'dataIndex')
            return `${aggTitle} : ${Globalize.formatNumber(e.value, format)}`
        }
    }

    const onRefresh = () => init(InitWijmo.init)
    const onAdded = () => setOptionsCall({ type: 'Added', title: '新增数据', data: columns })
    const onDelete = () => setOptionsCall({ type: 'Delete', title: '删除警告!', data: Data.currentItem, width: 600 })
    const onModify = () => setOptionsCall({ type: 'Modify', title: '修改数据', data: { columns, item: Data.currentItem } })
    const onSaveAct = () => saveFile(InitWijmo.init.getClipString(null, true, true), '选中数据.csv')
    const onSaveAll = () => {
        const rng = new CellRange(0, 0, InitWijmo.init.rows.length - 1, InitWijmo.init.columns.length - 1)
        saveFile(InitWijmo.init.getClipString(rng, true, true), '全部数据.csv')
    }

    const OptionsConfig = (e) => {
        const eventHandlers = {
            onRefresh,
            onAdded,
            onDelete,
            onModify,
            onSaveAct,
            onSaveAll,
        };
        const handler = eventHandlers[e]
        if (handler) handler()
        else console.error(`未找到事件 '${e}' 的处理程序`);
    }

    const ModalEvent = useEventEmitter()
    ModalEvent.useSubscription(val => {
        const { data, type } = val
        const { init } = InitWijmo
        if (type === 'Delete') init.collectionView.remove(data)
        if (type === 'Added') init.collectionView.addNew(data)
        if (type === 'Modify') {
            init.collectionView.editItem(Data.currentItem)
            Object.keys(Data.currentItem).forEach(key => Data.currentItem[key] = data[key])
            init.collectionView.commitEdit()
        }
    })


    return (
        <div className='WijmoFlexGrid'>
            <Dropdown menu={{ items: optionsBtn(OptionsConfig) }} trigger={['contextMenu']}>
                <div>
                    <FlexGrid
                        initialized={init}
                        itemsSource={Data}
                        {...configuration}
                    >
                        <FlexGridCellTemplate cellType="TopLeft" template={() => topText} />
                        {(addBtm || addSum) && <FlexGridCellTemplate cellType="BottomLeft" template={() => btmText} />}
                        <FlexGridCellTemplate cellType="RowHeader" template={e => addIndex ? e.row.index + 1 : ''} />
                        {filter && <FlexGridFilter />}
                        {columns.map(({ dataIndex, title, valueEnum, valueType, ...config }) => {
                            if (valueType === 'Hidden') return false
                            return (
                                <FlexGridColumn key={dataIndex} header={title} binding={dataIndex} dataMap={getDataMap(valueEnum || '')} {...config}>
                                    <FlexGridCellTemplate cellType="Group" template={CustonGroup} />
                                    <FlexGridCellTemplate cellType="ColumnFooter" template={CustonGroup} />
                                </FlexGridColumn>
                            )
                        })}
                    </FlexGrid>
                </div>
            </Dropdown>
            <ModelBox OptionsCall={OptionsCall} ModalEvent={ModalEvent} />
        </div>
    );
};

export default WijmoFlexGrid;